﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
namespace Adams.Admin.DataAccess.Donations
{
    public static class CreateBucket
    {
        public static Adams.Admin.DataTransfer.Donations.CreateBucket.PageLoad PageLoad(int id)
        {
            var data = new Adams.Admin.DataTransfer.Donations.CreateBucket.PageLoad();
            data.Bucket = new Shared.Entities.Donations.Bucket();

            if (id > 0)
            {
                using (SqlDataReader dr = DB.RunDataReader(@"
SELECT * FROM Donations.Buckets WHERE BucketID = @BucketID
", CommandType.Text,
                DB.CreateParameter("@BucketID", id, SqlDbType.Int)))
                {
                    dr.Read();
                    data.Bucket.ID = dr["BucketID"].DbInt();
                    data.Bucket.Name = dr["Name"].DbString();
                    data.Bucket.IsDefault = dr["IsDefault"].DbBool();
                    data.Bucket.AllowRecurring = dr["AllowRecurring"].DbBool();
                }
            }

            return data;
        }

        public static void Save(DataTransfer.Donations.CreateBucket.FormInput input)
        {
            DB.Run(@"
IF(@BucketID > 0)
BEGIN
    UPDATE Donations.Buckets SET
        Name = @Name
        ,IsDefault = @IsDefault
        ,AllowRecurring = @AllowRecurring
    WHERE BucketID = @BucketID
END
ELSE
BEGIN
    INSERT INTO Donations.Buckets (
        Name
        ,IsDefault
        ,AllowRecurring)
    VALUES (
        @Name
        ,@IsDefault
        ,@AllowRecurring)
    SET @BucketID = SCOPE_IDENTITY()
END

IF(@IsDefault = 1)
BEGIN
    UPDATE Donations.Buckets SET IsDefault = 0 WHERE BucketID <> @BucketID
END
    ", CommandType.Text,
                    DB.CreateParameter("@BucketID", input.ID.ToInt(), SqlDbType.Int),
                    DB.CreateParameter("@Name", input.Name.ToNString(), SqlDbType.VarChar, 50),
                    DB.CreateParameter("@IsDefault", input.IsDefault.ToBool(), SqlDbType.Bit),
                    DB.CreateParameter("@AllowRecurring", input.AllowRecurring.ToBool(), SqlDbType.Bit));
        }
    }
}
